package org.hrc.puzzleGame.view;

import org.hrc.puzzleGame.controller.LoginController;
import org.hrc.puzzleGame.model.User;
import org.hrc.puzzleGame.view.interfaces.Login;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.sql.SQLException;

public class LoginFrame extends DoorFrame implements Login {
    private LoginController loginController = new LoginController();

    //按钮
    //登录
   private static JButton loginJButton = new JButton(new ImageIcon("image\\login\\登录按钮.png"));
    //注册
   private static JButton registerJButton = new JButton(new ImageIcon("image\\login\\注册按钮.png"));

    //初始化对象
    public LoginFrame() {
        super();
        initButton();
        setVisible(true);
        setTitle("登录");
        // 添加背景图片
        background.setBounds(40, 40, 508, 560);
        container.add(background);
    }
    @Override
    //初始化按钮
    public void initButton() {
        super.initButton();
        //添加按钮
        //登录
         loginJButton.setBounds(100, 500, 120, 47);
         loginJButton.setBorder(new BevelBorder(7));
         loginJButton.addActionListener(this);
        container.add( loginJButton);
         loginJButton.setVisible(true);
        //注册
         registerJButton.setBounds(350, 500, 120, 47);
         registerJButton.setBorder(new BevelBorder(7));
         registerJButton.addActionListener(this);
         container.add(registerJButton);
         registerJButton.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        super.actionPerformed(e);
        Object obj = e.getSource();
        // 注册
        if (obj == registerJButton) {
            new RegisterFrame();
            setVisible(false);
        }
        //登录
        if (obj == loginJButton) {
            login();
        }
    }

    @Override
    //初始化登录按钮
    public boolean login() {
        if (!verify())
        return false;
        String userName = userNameJtextField.getText();
        String password = passwordJTextField.getText();
        User user = new User(userName, password);
        try {
            boolean login = loginController.login(user);
            if (login) {
                new GameFrame();
                setVisible(false);
                return true;
            } else {
                initDialog(new JLabel("密码错误或用户不存在"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
       return false;
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
        int keyCode = e.getKeyCode();
        System.out.println(keyCode);
        Object obj = e.getSource();
        if (keyCode == 10)
            login();
    }
}
